<template>
	<el-dialog :close-on-click-modal="false" :title="mainTitleName()" v-model="visible" :width="800" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px" label-position="right" v-loading.fullscreen="loading">
			<el-row>
				<el-col :span="24">
					<el-form-item label="标题" prop="title">
						<el-input v-model="form.title" placeholder="请输入文章标题" :maxlength="100" clearable
							show-word-limit></el-input>
					</el-form-item>
                    <template v-if="category == 4">
                        <el-form-item label="难度系数" prop="difficultyRate">
						    <el-input v-model="form.difficultyRate" placeholder="请输入难度系数"></el-input>
					    </el-form-item>
                        <el-form-item label="参考时长(秒)" prop="duration">
                            <el-input v-model="form.duration" placeholder="请输入参考时长"></el-input>
                        </el-form-item>
                        <el-form-item label="回答次数限制" prop="answerLimit">
                            <el-input v-model="form.answerLimit" placeholder="请输入回答次数限制"></el-input>
                            <div class="tips" style="line-height: 14px;margin-top: 10px;">0为无限制</div>
                        </el-form-item>
                        <el-form-item label="文章内容" prop="content">
                            <el-input :rows="6" type="textarea" v-model="form.content" placeholder="请输入文章内容"></el-input>
                        </el-form-item>
                      <el-form-item label="译文" prop="translate">
                        <el-input :rows="6" type="textarea" v-model="form.translate" placeholder="请输入译文内容"></el-input>
                      </el-form-item>
                    </template>
					<el-form-item label="状态" prop="status">
                        <el-radio-group v-model="form.status">
                            <el-radio :label="1">启用</el-radio>
                            <el-radio :label="0">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="排序号" prop="sort">
						<el-input v-model="form.sort" placeholder="请输入排序号"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>

</template>

<script>
export default {
	emits: ['success', 'closed'],
    components: {
    },
	props: {
		mainName: {
			type: String,
			default: () => {
				return '阅读文章'
			}
		},
	},
	data() {
		return {
			mode: "add",
			course: null,
            loading: false,
			visible: false,
			isSaveing: false,
            sentence: null,
			form: this.getDefaultRuleForm(),
			rules: {
				title: [
					{required: true, message: '请输入标题'}
				],
                difficultyRate: [
                    {
                        required: true, 
                        validator: (rule, value, callback) => {
                            var myreg = /^[1-5]$/;
                            if (value && !myreg.exec(value)) {
                                callback(new Error('只能输入1~5的数字'));
                            } else {
                                callback()
                            }
                        }
                    },
                ],
				duration: [
					{required: false, message: '请输入参考时长'},
				],
                content: [
                    {required: true, message: '请输入文章内容'}
                ],
                translate: [
                  {required: true, message: '请输入译文内容'}
                ],
                answerLimit: [
                    {
                        required: false,
                        validator: (rule, value, callback) => {
                            var myreg = /^(-|[0-9])\d*$/;
                            if (value && !myreg.exec(value)) {
                                callback(new Error('只能输入整数'))
                            } else {
                                callback()
                            }
                        }
                    },
                ],
                sort: [
                    {
                        required: false,
                        validator: (rule, value, callback) => {
                            var myreg = /^(-|[0-9])\d*$/;
                            if (value && !myreg.exec(value)) {
                                callback(new Error('只能输入整数'))
                            } else {
                                callback()
                            }
                        }
                    },
                ],
			},
            play: {
                src: '',
                type: 1,
                status: false
            },
            voiceFiles: [],
            translationVoiceFiles: [],
            category: 4
		}
	},
	mounted() {

	},
	methods: {
		//显示
		open(mode = 'add', category, course, sentence) {
			console.log('open', category)
			this.mode = mode;
			this.category = category;
			if (category === 4) {
				this.course = course
				this.form.courseId = course.id
				this.form.readType = 2
			}
			if (category === 8) {
				this.sentence = sentence
				this.form.courseId = sentence.courseId
				this.form.sentencesId = sentence.id
				this.form.readType = 1
			}
			this.visible = true;
			return this
		},
		//表单提交方法
		async submit() {
			if (!await this.$refs.dialogForm.validate().catch(() => { return false })) {
				return false
			}

            let _data = this.form
            
			try {
				this.isSaveing = true;
				if (this.form.id) {
					await this.$API.courseArticle.action.put(_data)
				} else {
					await this.$API.courseArticle.action.post(_data)
				}

				this.$emit('success')
				this.visible = false;
				this.$notify.success("保存成功")
			} finally {
				this.isSaveing = false;
			}
		},
		//表单注入数据
		async setData(row) {
            this.loading = true
			await this.$API.courseArticle.action.get({id: row.id}).then(res => {
                this.loading = false
                let _data = res.data
                let _form = {
                    id: _data.id,
                    title: _data.title,
                    readType: _data.readType.value,
                    difficultyRate: _data.difficultyRate,
                    duration: _data.duration,
                    answerLimit: _data.answerLimit,
                    content: _data.content,
                    translate: _data.translate,
                    courseId: _data.course ? _data.course.id : '',
                    status: _data.status ? _data.status.value : 1,
                    sort: _data.sort
                }

                this.form = _form
            }).finally(() => {
				this.loading = false
			})
        },
		getDefaultRuleForm() {
			return {
				id: null,
				title: '',
				difficultyRate: '',
                duration: '',
                answerLimit: '',
                content: '',
				courseId: '',
				status: 1,
                sort: '',
                sentencesId: '',
                readType: '',
			}
		},
        setAttrFile(file, type) {
            if (type == 'voice') {
                this.voiceFiles.push({
                    name: file.name,
                    path: file.path,
                    url: file.url,
                    tempImg: file.tempImg
                })
                this.form.voiceFile = file.url
            }else if (type == 'translationVoice') {
                this.translationVoiceFiles.push({
                    name: file.name,
                    path: file.path,
                    url: file.url,
                    tempImg: file.tempImg
                })
                this.form.translationVoiceFile = file.url
            }
        },
        //点击标签前往预览
        previewAttrFileItem(e, index, type) {
            if (type == 'voice') {
                let url = this.voiceFiles[index].tempImg
                this.canPlay(url, 1)
            } else if (type == 'translationVoice') {
                let url = this.translationVoiceFiles[index].tempImg
                this.canPlay(url, 1)
            } else {
                window.open(url)
            }
        },
        //移除单个文件
        delAttrFileItem(e, index, type) {
            if (type == 'voice') {
                this.voiceFiles.splice(index, 1)
            } else if (type == 'translationVoice') {
                this.translationVoiceFiles.splice(index, 1)
            }
        },
        getFileName(o) {
            var pos = o.lastIndexOf("/")
            return o.substring(pos + 1);
        },
        canPlay(url, type) {
            this.play.status = true
            this.play.type = type
            this.play.src = url

            this.$nextTick(() => {
                if (this.$refs.audioControls) {
                    this.$refs.audioControls.load()
                    this.$refs.audioControls.play()
                }
                this.$refs.videoControls && this.$refs.videoControls.load()
            })
        },
        closePlay(type) {
            if (type == 1) {
                this.$refs.audioControls && this.$refs.audioControls.pause()
            } else if (type == 2) {
                this.$refs.videoControls && this.$refs.videoControls.pause()
            }
            this.play.status = false
        },
        mainTitleName() {
			let titleName = '';
            console.log('this.category', this.category, this.course, this.sentence)
            let mainName = this.category === 8 ? '关卡' : '文章'
			if (!this.form.id && this.category === 4) {
				titleName = `添加【${this.course?.name}】${mainName}`;
			} else if (!this.form.id && this.category === 8) {
				titleName = `添加【${this.sentence?.title}】${mainName}`;
			} else {
				titleName = `编辑${mainName}`;
			}
			return titleName;
		}
	}
}
</script>

<style>
</style>
